package com.yeskery.nut.webhook.biz;

import com.yeskery.nut.annotation.bean.Component;
import com.yeskery.nut.websocket.Session;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;

/**
 * webhook biz
 * @author sprout
 * @version 1.0
 * 2023-06-03 17:27
 */
@Component
public class WebHookBiz {

    private static final Logger logger = Logger.getLogger(WebHookBiz.class.getName());

    private final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>(64);

    private final ConcurrentHashMap<String, String> sessionIdMap = new ConcurrentHashMap<>(64);

    private final CopyOnWriteArraySet<String> sessionIds = new CopyOnWriteArraySet<>();

    /**
     * 注册websocket session
     * @param session websocket session
     */
    public void registerWebsocketSession(String sessionId, Session session) {
        if (sessionIds.contains(sessionId)) {
            sessionIdMap.put(session.getId(), sessionId);
            Session preSession = sessions.put(sessionId, session);
            if (preSession != null) {
                preSession.close();
                logger.info("sessionId:" + sessionId + "，上一个连接已经关闭，session id:" + preSession.getId());
            }
        } else {
            session.close();
            logger.info("sessionId:" + sessionId + "无效，会话已关闭，session id:" + session.getId());
        }
    }

    /**
     * 关闭websocket session
     * @param session websocket session
     */
    public void closeWebsocketSession(Session session) {
        String sessionId = sessionIdMap.get(session.getId());
        sessionIdMap.remove(session.getId());
        sessionIds.remove(sessionId);
        sessions.remove(sessionId);
        session.close();
        logger.info("sessionId:" + sessionId + "会话id:" + session.getId() + "已关闭");
    }

    /**
     * 预添加sessionId
     * @param sessionId sessionId
     */
    public void beforeRegister(String sessionId) {
        sessionIds.add(sessionId);
    }

    /**
     * 获取websocket session
     * @param sessionId sessionId
     * @return websocket session
     */
    public Session getSession(String sessionId) {
        return sessions.get(sessionId);
    }
}
